package com.anlu.base.common.security.service;

import com.anlu.base.admin.api.dto.UserDTO;
import com.anlu.base.admin.api.dto.UserInfo;
import com.anlu.base.admin.api.feign.RemoteUserService;
import com.anlu.base.common.core.constant.CacheConstants;
import com.anlu.base.common.core.constant.SecurityConstants;
import com.anlu.base.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 用户的详细信息
 */
@Slf4j
@RequiredArgsConstructor
public class PigAppUserDetailsServiceImpl implements PigUserDetailsService{
    private final RemoteUserService remoteUserService;
    private final CacheManager cacheManager;

    /**
     * 手机号登录
     * @param phone
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if(cache != null && cache.get(phone) != null){
            return (PigUser) cache.get(phone).get();
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setPhone(phone);
        R<UserInfo> result = remoteUserService.info(userDTO);

        UserDetails userDetails = getUserDetails(result);
        if(cache != null){
            cache.put(phone,userDetails);
        }
        return userDetails;
    }

    @Override
    public UserDetails loadUserByUser(PigUser pigUser) {
        return this.loadUserByUsername(pigUser.getPhone());
    }

    /**
     * 是否支持此客户端校验
     * @param clientId 目标客户端
     * @return true/false
     */
    @Override
    public boolean support(String clientId, String grantType) {
        return SecurityConstants.MOBILE.equals(grantType);
    }
}
